package com.crm.miaohe.service;

import com.crm.miaohe.common.ApplicationConstant;
import com.crm.miaohe.controller.config.request.ConfigUpsertRequest;
import com.crm.miaohe.entity.dto.ConfigEntity;
import com.crm.miaohe.exception.ErpBusinessException;
import com.crm.miaohe.mapper.MstConfigMapper;
import com.crm.miaohe.model.MstConfig;
import com.crm.miaohe.model.MstConfigExample;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class ConfigServiceImpl implements ConfigService {

    private static final String CACHE_CONFIG_PREFIX = "sys:erp:config";

    private static final Logger LOGGER = LoggerFactory.getLogger(ConfigServiceImpl.class);

    private final MstConfigMapper configMapper;

    public ConfigServiceImpl(MstConfigMapper configMapper) {
        this.configMapper = configMapper;
    }

    @Override
    public List<ConfigEntity> getConfigs() {
        List<MstConfig> mstConfigs = configMapper.selectByExample(null);
        System.out.println("-============================= 使用了数据库！！！！！ ======================================");
        return mstConfigs.stream().map(config -> {
            ConfigEntity entity = new ConfigEntity();
            BeanUtils.copyProperties(config, entity);
            return entity;
        }).collect(Collectors.toList());
    }

    @Override
    public ConfigEntity addConfig(ConfigUpsertRequest request) {
        // 以防万一 ID 有值
        request.setId(null);
        MstConfig config = new MstConfig();
        BeanUtils.copyProperties(request, config);
        configMapper.insertSelective(config);
        return configToEntity(config);
    }

    @Override
    public void updateConfig(ConfigUpsertRequest request) {
        if (Objects.isNull(request.getId())) {
            throw new ErpBusinessException(HttpStatus.BAD_REQUEST, ApplicationConstant.ILLEGAL_PARAMETER, "id");
        }
        MstConfig config = configMapper.selectByPrimaryKey(request.getId());
        if (Objects.isNull(config)) {
            LOGGER.error("当前配置[{}]未找到，请刷新重试。", request.getId());
            throw new ErpBusinessException(HttpStatus.NOT_FOUND, ApplicationConstant.DATA_NOT_FOUND, request.getId());
        }
        config.setConfigKey(request.getConfigKey());
        config.setConfigValue(request.getConfigValue());
        configMapper.updateByPrimaryKeySelective(config);
    }

    @Override
    public void deleteConfig(String configKey) {
        MstConfigExample example = new MstConfigExample();
        example.createCriteria().andConfigKeyEqualTo(configKey);
        configMapper.deleteByExample(example);
    }

    @Override
    public ConfigEntity getConfig(String configKey) {
        MstConfigExample example = new MstConfigExample();
        example.createCriteria().andConfigKeyEqualTo(configKey);
        MstConfig config = configMapper.selectByExample(example).stream().findAny()
                .orElseThrow(() -> {
                    LOGGER.error("当前配置[{}]未找到，请刷新重试。", configKey);
                    return new ErpBusinessException(HttpStatus.NOT_FOUND, ApplicationConstant.DATA_NOT_FOUND, configKey);
                });
        return configToEntity(config);
    }

    private ConfigEntity configToEntity(MstConfig config) {
        ConfigEntity entity = new ConfigEntity();
        entity.setId(config.getId());
        entity.setConfigKey(config.getConfigKey());
        entity.setConfigValue(config.getConfigValue());
        return entity;
    }
}
